package com.example.gnenboot.demos.web;



import com.example.gnenboot.demos.domain.AjaxResult;
import com.example.gnenboot.demos.domain.AnalysisNMFReq;
import com.example.gnenboot.demos.domain.AnalysisReq;
import com.example.gnenboot.demos.service.ICommandRadapterService;
import com.example.gnenboot.demos.service.IRadapterService;
import com.example.gnenboot.demos.utils.FileUtils;
import com.example.gnenboot.demos.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/R")
public class RadapterController {
    @Autowired
    private IRadapterService iRadapterService;
    @Value("${resultFilePath}")
    private String resultFilePath;
    private static final String baseFilePach = "D:/Rworks/input";
    @Autowired
    private ICommandRadapterService commandRadapterService;
    @CrossOrigin
    @PostMapping("/list")
    @ResponseBody
    public AjaxResult list(){
        return AjaxResult.success("data",iRadapterService.targetFiles());
    }

    /**
     * 已不用，没有上传了
     * @param files
     */
    @CrossOrigin
    @PostMapping("/upload")
    @ResponseBody
    public void upload(@RequestParam("files") MultipartFile[] files) {
        try {
            iRadapterService.upload(files);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @param req
     *{
     * 	"gene" : "CX3CR1\nFGFBP2\nFCGR3A",
     * 	"expFiles" : "BLCA\nCESC",
     * 	"maxK" : 9,
     * 	"reps" : 1000,
     * 	"pItem" : 0.8,
     * 	"clusterNum" : 2,
     * 	"clusterAlg" : "km",
     * 	"distance" : "pearson",
     * 	"pFeature" : 1,
     * 	"seed" : 123456,
     * 	"plot" : "png"
     * }
     * @return
     */
    @CrossOrigin
    @PostMapping("/analysis")
    @ResponseBody
    public AjaxResult analysis(@RequestBody AnalysisReq req,HttpServletRequest request){
        //log.info("gene="+req.getGene());
        iRadapterService.writeParamFile(req.getGene());
        req.setIpAddr(getIp(request));
        //iRadapterService.analysis(req);
        commandRadapterService.analysis(req);
        return AjaxResult.success("analysis 分析完成...");

    }
    @CrossOrigin
    @PostMapping("/analysisNMF")
    @ResponseBody
    public AjaxResult analysisNMF(@RequestBody AnalysisNMFReq req,HttpServletRequest request){
        iRadapterService.writeParamFile(req.getGene());
        req.setIpAddr(getIp(request));
        commandRadapterService.analysisNMF(req);
        //iRadapterService.analysisNMF(req);
        //String expFile,String geneFile,String directory,String path
        /*String geneFile = "D:\\Rworks\\demo\\gene.txt";
        String expFile = "D:\\Rworks\\demo\\data\\ACC_norm.txt";
        String directory = "D:\\Rworks\\demo\\result";
        String path = "D:\\Rworks\\demo\\result\\sum data";
        RadapterServiceImpl.themis(expFile,geneFile,directory,path);*/

        return AjaxResult.success("analysisNMF 分析完成...");

    }

    /**
     * 已不用，分析完成后，直接下载
     * @return
     */
    @CrossOrigin
    @PostMapping("/show")
    @ResponseBody
    public AjaxResult show(){
        return AjaxResult.success("data",iRadapterService.show());

    }
    /**
     * 已不用，不涉及上传
     * @return
     */
    @CrossOrigin
    @PostMapping("/delete")
    @ResponseBody
    public AjaxResult delete(@RequestParam List<String> files,@RequestParam Integer type){
        iRadapterService.del(files,type);
        return AjaxResult.success();

    }
    @CrossOrigin
    @PostMapping("/download")
    @ResponseBody
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            delete = delete==null?false:delete;
            String ipAddr = getIp(request);
            if(iRadapterService.isFileAllBuilding()){
                iRadapterService.toZip();
                iRadapterService.delAll(resultFilePath);
            }
            File downLoadFile = iRadapterService.getLastModifiedFile();
            if(downLoadFile!=null){
                String fName = downLoadFile.getName();
                String filePath = downLoadFile.getAbsolutePath();
                if (!FileUtils.checkAllowDownload(fName)) {
                    throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 " , fileName));
                }
        /*String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
        String filePath = resultFilePath + fileName;*/

                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                FileUtils.setAttachmentResponseHeader(response, fName);
                FileUtils.writeBytes(filePath, response.getOutputStream());
                if (delete) {
                    FileUtils.deleteFile(filePath);
                }
            }
        } catch (Exception e) {
            log.error("下载文件失败" , e);
        }
    }
    /**
     *
     * @return
     */
    @CrossOrigin
    @PostMapping("/call")
    @ResponseBody
    public AjaxResult call(HttpServletRequest request){
        //String init = iRadapterService.sysInit("");
        String r = iRadapterService.sysCommand("a");
        String ip = getIp(request);
        return AjaxResult.success(r+";ip="+ip);

    }

    private String getIp(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-FORWARDED-FOR");
        InetAddress inet = null;
        try{
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
            inet = InetAddress.getLocalHost ();
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return inet.getHostAddress();
    }



}
